package wf.source.hrm.controller;

import org.springframework.web.bind.annotation.*;
import wf.source.hrm.util.AjaxResult;
import wf.source.hrm.util.RedisUtils;

import java.util.Map;

@RestController
@RequestMapping("/redis")
public class RedisController {
    //添加 key value expire
    @PostMapping
    public AjaxResult add(@RequestBody Map<String,Object> params){
        String key=(String) params.get("key");
        String value = (String) params.get("value");
        Object expireObj = params.get("expire");
        //有过期时间就设置一下过期时间
        try {
            if(expireObj!=null){
                Integer expire = Integer.valueOf(expireObj.toString());
                RedisUtils.INSTANCE.set(key,value,expire);
                return AjaxResult.me();
            }
            //没有过期时间就设置一下key value
            RedisUtils.INSTANCE.set(key,value);
            return AjaxResult.me();
        } catch (NumberFormatException e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("保存失败！"+e.getMessage());
        }
    }
    @GetMapping//获取
    public String get(@RequestParam(name = "key",required = true)String key){
        return RedisUtils.INSTANCE.get(key);
    }

    //删除
    @DeleteMapping
    public AjaxResult del(@RequestParam(name = "key",required = true)String key){
        try {
            RedisUtils.INSTANCE.del(key);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("删除失败！"+e.getMessage());
        }
    }
}
